package com.ywyt.publish;

import com.rabbitmq.client.*;
import com.ywyt.util.ConnUtil;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class SubscriptConsumer1 {
    public static final String QUEUE_NAME = "queue_name-01";
    @Test
    public void receive() throws IOException, TimeoutException {
        //1.获取连接对象
        Connection connection = ConnUtil.getConnection();
        //2.获取channel
        final Channel channel = connection.createChannel();
        //3.声明QUEUE
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        //4.绑定queue和exchange
        channel.queueBind(QUEUE_NAME,PublishProvider.EXCHANGE_NAME,"");
        channel.basicQos(1);
        //5.创建消费者
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消费者一号" + new String(body,"UTF-8"));
                //手动应答
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        //6.监听queue中的数据
        channel.basicConsume(QUEUE_NAME,false,consumer);
        System.in.read();
        //关闭资源
        channel.close();
        connection.close();
    }
}
